package org.dromara.curd.dnnyun.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.TreeBuildUtils;
import org.springframework.stereotype.Service;
import org.dromara.curd.dnnyun.domain.bo.DnnyunStoreBo;
import org.dromara.curd.dnnyun.domain.vo.DnnyunStoreVo;
import org.dromara.curd.dnnyun.domain.DnnyunStore;
import org.dromara.curd.dnnyun.mapper.DnnyunStoreMapper;
import org.dromara.curd.dnnyun.service.IDnnyunStoreService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 东云区域门店Service业务层处理
 *
 * @author wdm
 * @date 2024-02-28
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class DnnyunStoreServiceImpl implements IDnnyunStoreService {

    private final DnnyunStoreMapper baseMapper;

    /**
     * 查询东云区域门店
     */
    @Override
    public DnnyunStoreVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }


    /**
     * 查询东云区域门店列表
     */
    @Override
    public List<DnnyunStoreVo> queryList(DnnyunStoreBo bo) {
        LambdaQueryWrapper<DnnyunStore> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<Tree<Long>> buildTreeSelect(List<DnnyunStoreVo> dnnyunStoreVoList) {
        if (CollUtil.isEmpty(dnnyunStoreVoList)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(dnnyunStoreVoList, (DnnyunStoreVo, tree) ->
            tree.setId(DnnyunStoreVo.getId())
                .setParentId(DnnyunStoreVo.getParentId())
                .setName(DnnyunStoreVo.getStoreName())
                .setWeight(DnnyunStoreVo.getId()));
    }

    @Override
    public List<Tree<Long>> queryTreeList() {
        DnnyunStoreBo bo = new DnnyunStoreBo();
        List<DnnyunStoreVo> dnnyunStoreVoList = queryList(bo);

        return buildTreeSelect(dnnyunStoreVoList);
    }

    private LambdaQueryWrapper<DnnyunStore> buildQueryWrapper(DnnyunStoreBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DnnyunStore> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getId()!=null, DnnyunStore::getId, bo.getId());
        lqw.eq(bo.getParentId()!=null, DnnyunStore::getParentId, bo.getParentId());
        lqw.like(StringUtils.isNotBlank(bo.getStoreName()), DnnyunStore::getStoreName, bo.getStoreName());
        lqw.eq(bo.getParamcustom() != null, DnnyunStore::getParamcustom, bo.getParamcustom());
        lqw.like(StringUtils.isNotBlank(bo.getContactName()), DnnyunStore::getContactName, bo.getContactName());
        lqw.eq(StringUtils.isNotBlank(bo.getStorePhone()), DnnyunStore::getStorePhone, bo.getStorePhone());
        lqw.eq(bo.getStoreType() != null, DnnyunStore::getStoreType, bo.getStoreType());
        lqw.eq(bo.getType() != null, DnnyunStore::getType, bo.getType());
        lqw.like(StringUtils.isNotBlank(bo.getMobileShowName()), DnnyunStore::getMobileShowName, bo.getMobileShowName());
        lqw.eq(bo.getMobileShowFettle() != null, DnnyunStore::getMobileShowFettle, bo.getMobileShowFettle());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateUserNumber()), DnnyunStore::getCreateUserNumber, bo.getCreateUserNumber());
        return lqw;
    }

    /**
     * 新增东云区域门店
     */
    @Override
    public Boolean insertByBo(DnnyunStoreBo bo) {
        DnnyunStore add = MapstructUtils.convert(bo, DnnyunStore.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改东云区域门店
     */
    @Override
    public Boolean updateByBo(DnnyunStoreBo bo) {
        DnnyunStore update = MapstructUtils.convert(bo, DnnyunStore.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DnnyunStore entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除东云区域门店
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean deleteStore() {
        LambdaQueryWrapper<DnnyunStore> lqw = Wrappers.lambdaQuery();
        return baseMapper.delete(lqw)>0;
    }

    @Override
    public Boolean insertBatchByBo(List<DnnyunStoreBo> boList) {
        if(CollectionUtil.isNotEmpty(boList)){
            List<DnnyunStore> batchInsertList = new ArrayList<>();
            for (DnnyunStoreBo bo:boList) {
                DnnyunStore add = MapstructUtils.convert(bo, DnnyunStore.class);
                validEntityBeforeSave(add);
                batchInsertList.add(add);
            }
            return baseMapper.insertBatch(batchInsertList);
        }
        return true;
    }

    private void updateAncestors(List<DnnyunStore> dnnyunStoreList,String ancestors){
        if(CollectionUtil.isNotEmpty(dnnyunStoreList)){
            for (DnnyunStore store:dnnyunStoreList) {
                String nextAncestors = ""+store.getId();
                store.setAncestors(ancestors);
                baseMapper.updateById(store);;
                if(StringUtils.isNotBlank(ancestors)){
                    nextAncestors = ancestors+","+ store.getId();
                }
                //递归处理下级
                DnnyunStoreBo bo = new DnnyunStoreBo();
                bo.setParentId(store.getId());
                LambdaQueryWrapper<DnnyunStore> lqw = buildQueryWrapper(bo);
                List<DnnyunStore> childStoreList = baseMapper.selectList(lqw);
                updateAncestors(childStoreList,nextAncestors);
            }

        }
    }

    @Override
    public void refreshAncestors(Long storeId) {
        DnnyunStoreBo bo = new DnnyunStoreBo();
        String nextAncestors = "";
        if(storeId == null){
            //未上送storeId时，从0级开始刷新
            bo.setParentId(0L);
        }else{
            DnnyunStore store = baseMapper.selectById(storeId);
            if(StringUtils.isNotBlank(store.getAncestors())){
                nextAncestors = store.getAncestors()+","+store.getId();
            }else{
                nextAncestors = ""+store.getId();
            }
            bo.setParentId(storeId);
        }
        LambdaQueryWrapper<DnnyunStore> lqw = buildQueryWrapper(bo);
        List<DnnyunStore> dnnyunStoreList = baseMapper.selectList(lqw);
        updateAncestors(dnnyunStoreList,nextAncestors);
    }

}
